package com.bilibili.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author zuife
 * @description
 * @since 2024-05-02 22:17:55
 */
public class ABASolutionDemo {
    static AtomicInteger atomicInteger = new AtomicInteger(100);
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t" + "首次版本号：" + stamp);
            //暂停毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t" + "修改成功，当前最新值：" + atomicStampedReference.getReference() + "\t" + "当前版本号：" + atomicStampedReference.getStamp());
            //再次修改
            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t" + "修改成功，当前最新值：" + atomicStampedReference.getReference() + "\t" + "当前版本号：" + atomicStampedReference.getStamp());
        }, "t3").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t" + "首次版本号：" + stamp);
            //暂停毫秒，等待上面的t3线程,发生了ABA问题
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            boolean result = atomicStampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "\t" + (result ? "修改成功" : "修改失败") + "\t" + "当前最新值：" + atomicStampedReference.getReference() + "\t" + "当前版本号：" + atomicStampedReference.getStamp());
        }, "t4").start();

    }
}


